package ru.kest.babymonitor.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import ru.kest.babymonitor.Messenger;
import ru.kest.babymonitor.R;
import ru.kest.babymonitor.Settings;
import ru.kest.babymonitor.StartActivity;
import ru.kest.babymonitor.service.audio.AlarmPlayer;
import ru.kest.babymonitor.service.audio.AudioAnalyzer;
import ru.kest.babymonitor.service.audio.AudioHTTPReader;
import ru.kest.babymonitor.service.audio.AudioPlayer;

/**
 * Class Created by Konstantin Kharitonov on 01.08.2014.
 */
public class AudioService extends Service {

    private static String TAG = "IPCamBabyMonitorService";

    private Thread httpReaderThread = null;
    private Thread playerThread = null;
    private Thread audioAnalyzer = null;
    private final static int RECONNECT_TIME = 6000;

    private boolean tryToReconnect = false;

    private static boolean notification = false;

    Settings settings = Settings.getInstance();

    Handler handler = new Handler();
    Runnable aliveTimer = new Runnable() {

        @Override
        public void run() {
            if (tryToReconnect && isHTTPReaderThreadAlive()) {
                tryToReconnect = false;
                Messenger.getInstance().put(Messenger.RESUME_VIDEO);
            }
            if (settings.isAudioServiceShouldWork() && !isHTTPReaderThreadAlive()) {
                startHTTPReader();
//                AlarmPlayer.getInstance().playAlarm();
                tryToReconnect = true;
            }
            AlarmPlayer alarmPlayer = AlarmPlayer.getInstance();
            if (alarmPlayer.checkIsAlarmTimeoutExpired()) {
//                Messenger.getInstance().put(Messenger.REFRESH_MENU_PANEL);
                Log.d(TAG, "alarmPlayer.checkIsAlarmTimeoutExpired()");
            }
            if (!settings.isAlarmOn() && notification) {
                stopForeground(true);
                notification = false;
            }

            handler.postDelayed(this, RECONNECT_TIME);
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG, "AudioService Created!");
        if (settings.isAudioServiceShouldWork()) {
            startThreads();
        }
        handler.postDelayed(aliveTimer, RECONNECT_TIME);
    }

    private void startThreads() {
        startHTTPReader();
        if (!isPlayerThreadAlive()) {
            playerThread = new Thread(new AudioPlayer());
            playerThread.start();
        }
        if (!isAnalyzerThreadAlive()) {
            audioAnalyzer = new Thread(new AudioAnalyzer());
            audioAnalyzer.start();
        }
    }

    private synchronized void startHTTPReader() {
        if (!isHTTPReaderThreadAlive()) {
            httpReaderThread = new Thread(new AudioHTTPReader());
            httpReaderThread.start();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startThreads();
        if (settings.isAlarmOn() && !notification) {
            Intent startActivityIntent = new Intent(this, StartActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this,
                    0, startActivityIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("IP Cam notification")
                    .setContentText("Включен анализ звука камеры")
                    .setContentIntent(contentIntent);

            startForeground(1, builder.getNotification());
            notification = true;
        }
        Log.i(TAG, "AudioService started!");
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (isHTTPReaderThreadAlive()) {
            httpReaderThread.interrupt();
            httpReaderThread = null;
        }
        if (isPlayerThreadAlive()) {
            playerThread.interrupt();
            playerThread = null;
        }
        if (isAnalyzerThreadAlive()) {
            audioAnalyzer.interrupt();
            audioAnalyzer = null;
        }
    }

    private boolean isHTTPReaderThreadAlive() {
        return httpReaderThread != null && httpReaderThread.isAlive();
    }

    private boolean isPlayerThreadAlive() {
        return playerThread != null && playerThread.isAlive();
    }

    private boolean isAnalyzerThreadAlive() {
        return audioAnalyzer != null && audioAnalyzer.isAlive();
    }
}
